/*
 * Copyright 2025 The JA-SIG Collaborative. All rights reserved.
 * distributed with this file and available online at
 */
package com.lap.auth.adapter.driving.persistence.user.repository;

import com.lap.auth.adapter.driving.persistence.user.UserCache;
import com.lap.auth.adapter.driving.persistence.user.mapper.UserRoleMapper;
import com.lap.auth.adapter.driving.persistence.user.po.UserRolePo;
import com.lap.auth.domain.user.repository.UserRoleRepository;
import java.util.List;
import java.util.Set;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;

@RequiredArgsConstructor
@Repository
public class UserRoleRepositoryImpl implements UserRoleRepository {

  private final UserRoleMapper userRoleMapper;

  @CacheEvict(value = UserCache.USER_ROLE, key = "#userId")
  @Override
  public void saveAll(Integer userId, Set<Integer> roleIdSet) {
    List<UserRolePo> list =
        roleIdSet.stream().map(roleId -> new UserRolePo(userId, roleId)).toList();
    userRoleMapper.insertBatch(list);
  }

  @CacheEvict(value = UserCache.USER_ROLE, key = "#userId")
  @Override
  public void deleteByUserId(Integer userId) {
    userRoleMapper.deleteByUserId(userId);
  }

  @Cacheable(value = UserCache.USER_ROLE, key = "#userId")
  @Override
  public List<Integer> findByUserId(Integer userId) {
    return userRoleMapper.selectByUserId(userId);
  }
}
